package com.example.lock;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.db.Db;
import cn.hutool.db.DbUtil;
import cn.hutool.db.Entity;
import cn.hutool.db.ds.DSFactory;
import org.junit.Test;

import java.sql.SQLException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Logger;

/**
 * @author csp 2023-10-25
 */
public class MysqlLockExample {


    @Test
    public void init() throws SQLException {
        Db db = getDataSource();
        for (int i = 0; i < 1000; i++) {
            int tId = RandomUtil.randomInt(100);
            int cId = RandomUtil.randomInt(10);
            String name = RandomUtil.randomString(RandomUtil.BASE_CHAR, 3);
            db.insert(Entity.create("test_table")
                    .addFieldNames("teacher_id", "class_id", "name")
                    .set("teacher_id", tId)
                    .set("class_id", cId)
                    .set("name", name)
            );
        }
    }

    @Test
    public  void lockTest() throws SQLException {

        ExecutorService service = Executors.newFixedThreadPool(10);
        Db db = getDataSource();
        for (int i = 0; i < 100000; i++) {
            int tId = RandomUtil.randomInt(100);
            int cId = RandomUtil.randomInt(10);
            String name = RandomUtil.randomString(RandomUtil.BASE_CHAR, 3);
            db.update(
                    Entity.create().set("name", name),
                    Entity.create("test_table").set("teacher_id", tId).set("class_id", cId)
            );
        }
    }

    private static Db getDataSource() {
        return DbUtil.use(DSFactory.get("lock_test"));
    }
}
